<template>
  <van-nav-bar :title="t('refund.returnInfo')" left-arrow @click-left="onClickLeft" placeholder fixed />
  <van-cell-group v-if="!loading">
    <van-row gutter="10" class="van-cell van-cell--center">
      <van-col span="17">
        <van-row class="van-cell__title">{{ t('refund.returnNo') + orderInfo.returnNo }}</van-row>
        <van-row class="van-cell__label">{{ t('refund.customer') + orderInfo.customCode + ' / ' + orderInfo.customName }}</van-row>
      </van-col>
      <van-col span="7" class="text-right">
        <span class="font-bold text-black">{{ fileList?.length > 0 ? t('refund.photoed') : t('refund.unphotoed') }}</span>
      </van-col>
    </van-row>
  </van-cell-group>
  <van-field ref="skuCodeRef" v-model="skuCode" size="large" @keydown.enter="handleScanSku" :placeholder="t('refund.pleaseScanSku')" clearable>
    <template #left-icon>
      <van-icon name="enlarge" size="1.5rem" class="px-2"/>
    </template>
  </van-field>
  <van-collapse v-model="currentSkuIndex" accordion>
    <van-collapse-item v-for="(sku, i) in orderInfo.orderSkuBOList" :key="i" :name="i">
      <template #title>
        <span class="font-bold">{{ sku.skuCode }}</span>
      </template>
      <van-cell :title="t('refund.preNum')" :value="sku.skuNum" />
      <van-field name="location" required label-align="top">
        <template #label>
          <van-row class="w-full" gutter="10">
            <van-col span="14">
              {{ t('refund.locationAndNum') }}
            </van-col>
            <van-col span="10" class="text-right text-green-500">
              <van-icon name="plus" @click="sku.locations.push({})"/>
            </van-col>
          </van-row>
        </template>
        <template #input>
          <van-row>
            <van-swipe-cell v-for="(location, i) in sku.locations" :key="i" class="mb-1">
              <van-row gutter="10">
                <van-col span="18">
                  <van-field v-model="location.locationCode" :placeholder="t('refund.pleaseScanLocation')" clearable class="input-border">
                    <template #left-icon>
                      <van-icon name="enlarge" size="1.5rem" class="pr-2"/>
                    </template>
                  </van-field>
                </van-col>
                <van-col span="6">
                  <van-field v-model="location.shelveNum" type="digit" clearable class="input-border" />
                </van-col>
              </van-row>
              <template v-if="sku.locations.length > 1" #right>
                <div class="pl-2">
                  <van-button type="danger" icon="delete" @click="sku.locations.splice(i, 1)" />
                </div>
              </template>
            </van-swipe-cell>
          </van-row>
        </template>
      </van-field>
      <van-field name="size" required label-align="top">
        <template #label>
          <van-row class="w-full" gutter="10">
            <van-col span="14">
              {{ t('inbound.realSize') }}
            </van-col>
            <van-col span="10" class="text-right text-gray-500">
              {{ sku.skuLength }} * {{ sku.skuWidth }} * {{ sku.skuHeight }} CM
            </van-col>
          </van-row>
        </template>
        <template #input>
          <van-row gutter="10">
            <van-col span="7">
              <van-field v-model="sku.realLength" type="number" clearable class="input-border" />
            </van-col>
            <van-col span="7">
              <van-field v-model="sku.realWidth" type="number" clearable class="input-border" />
            </van-col>
            <van-col span="10">
              <van-field v-model="sku.realHeight" type="number" clearable class="input-border">
                <template #right-icon>
                  CM
                </template>
              </van-field>
            </van-col>
          </van-row>
        </template>
      </van-field>
      <van-field name="weight" required label-align="top">
        <template #label>
          <van-row class="w-full" gutter="10">
            <van-col span="14">
              {{ t('inbound.realWeight') }}
            </van-col>
            <van-col span="10" class="text-right text-gray-500">
              {{ sku.skuWeight }} KG
            </van-col>
          </van-row>
        </template>
        <template #input>
          <van-field v-model="sku.realWeight" type="number" clearable class="input-border">
            <template #right-icon>
              KG
            </template>
          </van-field>
        </template>
      </van-field>
    </van-collapse-item>
  </van-collapse>
  <van-field v-model="orderInfo.packagingStatusText" is-link readonly :label="t('refund.packagingStatus')" name="packagingStatus" required @click="showPackagingStatus = true" />
  <van-field :label="t('refund.photo')" required label-align="top">
    <template #input>
      <van-uploader v-model="fileList" multiple :max-count="3" />
    </template>
  </van-field>
  <van-field :label="t('refund.remark')" name="remark" label-align="top">
    <template #input>
      <van-field v-model="orderInfo.remark" clearable class="input-border" />
    </template>
  </van-field>
  <van-action-bar placeholder>
    <van-row gutter="10" class="w-full p-1">
      <van-col span="12">
        <van-button class="text-base" block plain @click="onClickLeft">{{ t('cancel') }}</van-button>
      </van-col>
      <van-col span="12">
        <van-button class="text-base" :loading="confirmLoading" block type="primary" @click="confirmShelve">{{ t('refund.inboundConfirm') }}</van-button>
      </van-col>
    </van-row>
  </van-action-bar>
  <van-back-top />
  <van-popup v-model:show="showPackagingStatus" position="bottom">
    <van-picker :confirm-button-text="t('confirm')" :cancel-button-text="t('cancel')" :columns="packagingStatusEnums" @confirm="selectPackagingStatus" @cancel="showPackagingStatus = false" />
  </van-popup>
</template>

<script setup lang="ts">
import { useI18n } from "vue-i18n";
import { postRequest, scanSuccess, scanFail } from "@/api";
import { useRoute } from "vue-router";
import { AppToast } from "@/utils/appToast";

const query = useRoute().query;
const { t } = useI18n();
const onClickLeft = () => history.back();

const loading = ref(true);
const confirmLoading = ref(false);
const showPackagingStatus = ref(false);
const orderInfo: any = ref({});
const skuCode = ref();
const skuCodeRef = ref();
const fileList = ref([]);

const currentSkuIndex = ref(0);

onMounted(() => {
  skuCodeRef.value.focus()
  loadOrderInfo()
});

const packagingStatusEnums = [
  { text: t('enums.packagingStatus.packagingOk'), value: 0 },
  { text: t('enums.packagingStatus.packagingDirty'), value: 1 },
  { text: t('enums.packagingStatus.packagingBroken'), value: 2 }
];

const loadOrderInfo = () => {
  postRequest("/inbound/getReturnEnterByNo", { number: query.returnNo }).then(res => {
    res.data.orderSkuBOList.forEach(item => {
      item.realLength = item.skuLength
      item.realWidth = item.skuWidth
      item.realHeight = item.skuHeight
      item.realWeight = item.skuWeight
      item.locations = [{}]
    })
    orderInfo.value = res.data;
  }).finally(() => {
    loading.value = false;
  })
};

const handleScanSku = () => {
  const index = orderInfo.value.orderSkuBOList.findIndex(item => item.skuCode.toLowerCase() === skuCode.value.toLowerCase())
  if (index >= 0) {
    currentSkuIndex.value = index
    scanSuccess()
  } else {
    scanFail();
  }
  skuCode.value = null
};

const selectPackagingStatus = ({ selectedOptions }) => {
  orderInfo.value.packagingStatusText = selectedOptions[0]?.text;
  orderInfo.value.packagingStatus = selectedOptions[0]?.value;
  showPackagingStatus.value = false;
};

const validateSku = (sku: any) => {
  return sku.realLength > 0 && sku.realWidth > 0 && sku.realHeight > 0 && sku.realWeight > 0 &&
      sku.realWeight > 0 && !sku.locations.find(item => !(item.shelveNum > 0 && item.locationCode))
}

const confirmShelve = () => {
  confirmLoading.value = true
  const formData: FormData = new FormData()
  formData.set('id', orderInfo.value.id);
  let index = 0
  for (let i = 0; i < orderInfo.value.orderSkuBOList.length; i++) {
    const sku = orderInfo.value.orderSkuBOList[i]
    if (!validateSku(sku)) {
      currentSkuIndex.value = i
      AppToast(t("pleaseCheckRequired"), "danger", true);
      confirmLoading.value = false
      return
    }
    sku.locations.forEach(location => {
      formData.set(`returnSkuList[${index}].skuId`, sku.skuId);
      formData.set(`returnSkuList[${index}].skuLength`, sku.realLength);
      formData.set(`returnSkuList[${index}].skuWidth`, sku.realWidth);
      formData.set(`returnSkuList[${index}].skuHeight`, sku.realHeight);
      formData.set(`returnSkuList[${index}].skuWeight`, sku.realWeight);
      formData.set(`returnSkuList[${index}].skuNum`, location.shelveNum);
      formData.set(`returnSkuList[${index}].locationCode`, location.locationCode);
      index ++
    })
  }
  if (orderInfo.value.packagingStatus === null || fileList.value.length <= 0) {
    AppToast(t("pleaseCheckRequired"), "danger", true);
    confirmLoading.value = false
    return
  }
  formData.set(`packagingStatus`, orderInfo.value.packagingStatus);
  formData.set("outerPackage",fileList.value[0]?.file);
  formData.set("productPackage",fileList.value[1]?.file);
  formData.set('productPhoto', fileList.value[2]?.file);
  postRequest('inbound/returnShelve', formData).then(() => {
    AppToast(t("refund.inboundSuccess"), "success")
    history.back()
  }).finally(() => {
    confirmLoading.value = false
  })
}
</script>

<style scoped lang="less">
:deep(.van-cell) {
  font-size: 1rem;
}

:deep(.van-nav-bar__title) {
  font-size: 1rem;
  font-weight: 500;
  color: white;
}

:deep(.van-nav-bar__content) {
  background: #1b82d2;
}

:deep(.van-nav-bar .van-icon) {
  color: white;
}

:deep(.van-collapse-item__content) {
  padding: 0;
}

:deep(.input-border) {
  border: 1px solid #e5e7eb;
}
</style>
